<?php

class lqInput implements ArrayAccess
{
	private $sources;

	public function __construct ()
	{
		$this->accept = array();

		// If page request was done by post, use post fields by default
		if (isset($_SERVER['REQUEST_METHOD']) &&
			$_SERVER['REQUEST_METHOD'] == 'POST')
		{
			$this->accept('POST');
		}
		else
		{
			$this->accept('GET');
		}
	}

	public function accept ($source)
	{
		// Either allow sources as an array or list of arguments
		if (is_array($source))
		{
			$sources = array_values($source);
		}
		else
		{
			$sources = func_get_args();
		}

		// Make sure all sources are valid
		foreach ($sources as $key => $source)
		{
			$source = strtoupper($source);

			if (!in_array($source, array('GET', 'POST', 'COOKIE')))
			{
				throw new lqInputException("Unknown input source '$source'");
			}

			$sources[$key] = "_$source";
		}

		$this->sources = $sources;
	}

	private function handleInput ($input)
	{
		// Handle input arrays recursively
		if (is_array($input))
		{
			foreach ($input as $key => $value)
			{
				$input[$key] = $this->handleInput($value);
			}
		}
		else
		{
			$input = get_magic_quotes_gpc() ? stripslashes($input) : $input;
			$input = trim($input);
		}

		return $input;
	}

	public function offsetExists ($offset)
	{
		foreach ($this->sources as $source)
		{
			if (isset($GLOBALS[$source][$offset]))
			{
				return true;
			}
		}

		return false;
	}

	public function offsetGet ($offset)
	{
		foreach ($this->sources as $source)
		{
			if (isset($GLOBALS[$source][$offset]))
			{
				return $this->handleInput($GLOBALS[$source][$offset]);
			}
		}

		return false;
	}

	public function offsetSet ($offset, $value)
	{
		throw new lqInputException('Cannot define user input values');
	}

	public function offsetUnset ($offset)
	{
		throw new lqInputException('Cannot unset user input values');
	}
}

?>